
package com.fl.util.compress;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;

/**
 * zip文件格式压缩实现<br>
 * 调用Aapache Commons Compress包中的
 * 
 * <pre>
 * ZipArchiveInputStream 
 * ZipArchiveOutputStream
 * </pre>
 * 
 * 实现<br>
 * 
 */
public class ZipCompressor extends AbstractFileCompressor {

    /**
     * 构造函数 <br>
     * */
    public ZipCompressor() {
        super();
    }
    
    /**
     * 使用zip格式压缩文件<br>
     * 
     * @see com.unionpay.common.util.compress.FileCompressor#compress(java.io.File, java.io.File)
     */
    @Override
    public void compress(File srcFile, File destFile) throws IOException {
        ZipArchiveOutputStream out = null;
        InputStream is = null;
        try {
            is = new BufferedInputStream(new FileInputStream(srcFile), buffSize);
            out = new ZipArchiveOutputStream(new BufferedOutputStream(new FileOutputStream(destFile), buffSize));
            ZipArchiveEntry entry = new ZipArchiveEntry(srcFile.getName());
            entry.setSize(srcFile.length());
            out.putArchiveEntry(entry);
            copyStreams(is, out);
            out.closeArchiveEntry();
        } finally {
            closeStreams(is);
            closeStreams(out);
        }

    }
    
    /**
     * 使用zip格式解压缩文件<br>
     * 
     * @see com.unionpay.common.util.compress.FileCompressor#decompress(java.io.File, java.io.File)
     */
    @Override
    public void decompress(File srcFile, File destDir) throws IOException {
        ZipArchiveInputStream is = null;
        try {
            is = new ZipArchiveInputStream(new BufferedInputStream(new FileInputStream(srcFile), buffSize));
            ZipArchiveEntry entry = null;
            while ((entry = is.getNextZipEntry()) != null) {
                if (entry.isDirectory()) {
                    File directory = new File(destDir, entry.getName());
                    directory.mkdirs();
                } else {
                    OutputStream os = null;
                    try {
                        os = new BufferedOutputStream(new FileOutputStream(new File(destDir, entry.getName())),
                                buffSize);
                        copyStreams(is, os);
                    } finally {
                        closeStreams(os);
                    }
                }
            }
        } finally {
            closeStreams(is);
        }

    }
}
